<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/7/31
 * Time: 上午9:38
 */
namespace backend\controllers;

use common\models\ar\ActivationDetail;
use common\models\ar\ActivationItem;
use common\models\ar\HistoryUserInfoAlter;
use common\models\ar\User;
use common\models\Common;
use common\models\UserDao;
use common\models\ar\UserBrokers;

class AccountController extends BackendController
{
    /**
     * 个人中心
     */
    public function actionCenter()
    {
        //利率
        $uid = \Yii::$app->user->identity->userID;
        $userInfo = User::findOne($uid);
        $userbrokers=UserBrokers::findOne(['loginName'=>$userInfo->loginName]);
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);
        if ($userInfo->loginName=='admin')
        {
            $Where_s="WHERE level=1";
            $Where_s1="level=2";
        }else{
            $Where_s="WHERE agentID={$userbrokers->id} && level=1";
            $Where_s1="agentID={$userbrokers->id} && level=2";
        }
        //各层级人数
        $sql = "SELECT 
                  count(*) count
                FROM 
                  `user` a  {$Where_s}";
        $tmp1 = \Yii::$app->db->createCommand($sql)->queryAll();

        $sql = "SELECT 
                  count(*) count
                FROM 
                  `user` a 
                  WHERE
                  {$Where_s1}";
        $tmp2 = \Yii::$app->db->createCommand($sql)->queryAll();

        $hierarchy = array_merge($tmp1, $tmp2);
        return $this->renderPartial('index', [
            'is_first' => $levelInfo['is_first'],
            'is_last' => $levelInfo['is_last'],
            'userInfo' => $userInfo,
            'userbrokers_id'=>$userbrokers['id'],
            'hierarchy' => $hierarchy,
        ]);
    }


    /**
     * 创建直属层级链
     * @return string
     */
    public function actionAddDirectLinks()
    {
        $uid = \Yii::$app->user->identity->uid;

        $req = \Yii::$app->request;
        if (\Yii::$app->user->identity->direct_links != '') {
            $code = 1002;
            $msg = '返佣账户已创建';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $password = trim($req->post('password', ''));
        $passwordConfirm = trim($req->post('password_confirm', ''));

        if (strlen($password) < 6) {
            $code = 1003;
            $msg = '密码长度不能小于6位';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($password != $passwordConfirm) {
            $code = 1004;
            $msg = '确认密码检验失败：两次密码不一致';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $bool = UserDao::createDirectLinks($uid, $password, time(), '', $req->userIP, $req->userAgent);
        if ($bool) {
            UserDao::activation($uid);

            $code = 1;
            $msg = "创建成功";

        } else {
            $code = 0;
            $msg = "创建失败";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }


    /**
     * 修改用户信息
     */
    public function actionSetForm()
    {
        $uid = \Yii::$app->user->identity->uid;
        $obj = User::findOne($uid);

        return $this->renderPartial('set-form', ['info' => $obj]);
    }

    /**
     * 提交修改
     */
    public function actionSet()
    {
        $req = \Yii::$app->request;
        $uid = \Yii::$app->user->identity->uid;
        $obj = User::findOne($uid);

        $password = trim($req->post('password', ''));
        $passwordConfirm = trim($req->post('password_confirm', ''));

        $safeCode = trim($req->post('safe_code', ''));
        $safeCodeConfirm = trim($req->post('safe_code_confirm', ''));

        $setArr = [];
        if ($password != '') {
            if (strlen($password) < 6) {
                $code = 1003;
                $msg = '密码长度不能小于6位';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }

            if ($password != $passwordConfirm) {
                $code = 1002;
                $msg = '两次密码不一致';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }

            $setArr['password'] = md5(md5($password) . $obj->password_salt);
        }

        if ($safeCode != '') {
            $check = Common::dataCheck($safeCode, [
                'type' => 3,
                'detail' => [
                    'pattern' => '/[a-zA-Z0-9]{4,8}$/',
                    'info' => '由大小写字母、数字组成的长度为4-8位的字符串',
                ]
            ]);
            if ($check['code'] != 1) {
                $code = 1003;
                $msg = '安全码检验失败：' . $check['msg'];
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }

            if ($safeCode != $safeCodeConfirm) {
                $code = 1003;
                $msg = '两次安全码不一致';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }

            $setArr['safe_code'] = $safeCode;
        }

        if (empty($setArr)) {
            $code = 1004;
            $msg = '请输入要修改的内容';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $mySafeCode = trim($req->post('my_safe_code', ''));
        if ($mySafeCode != $obj->safe_code) {
            $code = 1005;
            $msg = '安全码不正确';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $obj->attributes = $setArr;
        $obj->save();

        $time = time();
        if (array_key_exists('password', $setArr)) {
            $history = new HistoryUserInfoAlter();
            $history->attributes = [
                'uid_operate' => $uid,
                'uid' => $uid,
                'type' => 2,
                'create_time' => $time,
                'ip' => $req->userIP,
                'ua' => $req->userAgent,
                'remark' => json_encode(['password' => $password])
            ];
            $history->save();
        }

        if (array_key_exists('safe_code', $setArr)) {
            $history = new HistoryUserInfoAlter();
            $history->attributes = [
                'uid_operate' => $uid,
                'uid' => $uid,
                'type' => 4,
                'create_time' => $time,
                'ip' => $req->userIP,
                'ua' => $req->userAgent,
                'remark' => json_encode(['safe_code' => $safeCode])
            ];
            $history->save();
        }

        exit(json_encode(['code' => 1, 'msg' => '修改成功']));
    }

    /**
     * 获取账户信息
     */
    public function actionInfo()
    {
        $uid = \Yii::$app->user->identity->uid;
        $level = \Yii::$app->user->identity->level;
        $userInfo = User::findOne($uid);
        $levelInfo = Common::getLevelsInfo($level);

        //1账户信息，2推广信息，3实名信息，4直属层级链信息，5成本信息
        $type = \Yii::$app->request->get('type', 1);

        if ($type == 1) {
            return $this->renderPartial('info_1', ['userInfo' => $userInfo]);
        }

        if ($type == 2) {
            //各层级人数
            $sql = "SELECT 
                      count(1) count,
                      a.`level`,
                      b.`name`
                    FROM 
                      `user` a 
                    LEFT JOIN `level` b ON a.`level` = b.`id`
                    WHERE 
                      a.`uid_level_" . $level . "` = " . $uid . " 
                    GROUP BY a.`level`,b.`name`
                    ORDER BY a.`level` ASC
            ";
            $tmp1 = \Yii::$app->db->createCommand($sql)->queryAll();
            $sql = "SELECT 
                      count(1) count,
                      a.`level`,
                      b.`name`
                    FROM 
                      `user_trade` a 
                    LEFT JOIN `level` b ON a.`level` = b.`id`
                    WHERE 
                      a.`uid_level_" . $level . "` = " . $uid . " 
                    GROUP BY a.`level`,b.`name`
                    ORDER BY a.`level` ASC
            ";
            $tmp2 = \Yii::$app->db->createCommand($sql)->queryAll();
            $hierarchy = array_merge($tmp1, $tmp2);

            return $this->renderPartial('info_2', [
                'userInfo' => $userInfo,
                'hierarchy' => $hierarchy,
                'is_last' => $levelInfo['is_last'] ? true : false,
            ]);
        }

        if ($type == 3) {
            return $this->renderPartial('info_3');
        }

        if ($type == 4) {
            $direct_hierarchy = [];
            $direct_links = \Yii::$app->user->identity->direct_links;
            if ($direct_links != '') {
                $sql = "SELECT 
                          a.`alias`,
                          a.`clientSN`,
                          b.`name` 
                        FROM 
                          `user` a 
                        LEFT JOIN `level` b ON a.`level` = b.`id` 
                        WHERE 
                          a.`uid` IN (" . $direct_links . ")
                        ORDER BY a.`level` ASC
                ";
                $tmp1 = \Yii::$app->db->createCommand($sql)->queryAll();

                $bind_user_trade = \Yii::$app->user->identity->bind_user_trade;
                $sql = "SELECT 
                          a.`alias`,
                          a.`clientSN`,
                          b.`name` 
                        FROM 
                          `user_trade` a 
                        LEFT JOIN `level` b ON a.`level` = b.`id` 
                        WHERE 
                          a.`uid` = " . $bind_user_trade . "
                ";
                $tmp2 = \Yii::$app->db->createCommand($sql)->queryAll();

                $direct_hierarchy = array_merge($tmp1, $tmp2);
            }
            return $this->renderPartial('info_4', ['direct_hierarchy' => $direct_hierarchy]);
        }
    }

    public function actionActivation()
    {
        $uid = \Yii::$app->user->identity->uid;
        $tmp = ActivationItem::find()->where(['is_show' => 1])->orderBy(['sort' => 'asc'])->asArray()->all();
        $items = [];
        foreach ($tmp as $v) {
            $items[$v['id']] = $v;
        }

        $tmp = ActivationDetail::find()->where(['uid' => $uid])->asArray()->all();
        $finished = [];
        foreach ($tmp as $t) {
            $finished[$t['item_id']] = $t;
        }

        return $this->renderPartial('activation', ['items' => $items, 'finished' => $finished]);
    }

    public function actionActivationItem()
    {
        $id = \Yii::$app->request->get('id', 0);
        $info = [];
        $info['detail'] = ActivationDetail::find()->where([
            'uid' => \Yii::$app->user->identity->uid,
            'item_id' => $id
        ])->one();

        if ($id == 4) {
            $direct_hierarchy = [];
            $direct_links = \Yii::$app->user->identity->direct_links;
            if ($direct_links != '') {
                $sql = "SELECT 
                          a.`alias`,
                          a.`clientSN`,
                          b.`name` 
                        FROM 
                          `user` a 
                        LEFT JOIN `level` b ON a.`level` = b.`id` 
                        WHERE 
                          a.`uid` IN (" . $direct_links . ")
                ";

                $tmp1 = \Yii::$app->db->createCommand($sql)->queryAll();

                $bind_user_trade = \Yii::$app->user->identity->bind_user_trade;
                $sql = "SELECT 
                          a.`alias`,
                          a.`clientSN`,
                          b.`name` 
                        FROM 
                          `user_trade` a 
                        LEFT JOIN `level` b ON a.`level` = b.`id` 
                        WHERE 
                          a.`uid` = " . $bind_user_trade . "
                ";
                $tmp2 = \Yii::$app->db->createCommand($sql)->queryAll();

                $direct_hierarchy = array_merge($tmp1, $tmp2);
            }
            $info['direct_hierarchy'] = $direct_hierarchy;
        }

        return $this->renderPartial('activation-' . $id, $info);
    }

    public function actionActivationOperate()
    {
        $uid = \Yii::$app->user->identity->uid;

        $id = \Yii::$app->request->get('id', 0);
        $tmp = ActivationDetail::find()->where([
            'uid' => $uid,
            'item_id' => $id
        ])->count();

        $time = time();
        if (!$tmp) {
            $obj = new ActivationDetail();
            $obj->attributes = [
                'uid' => $uid,
                'item_id' => $id,
                'time' => $time
            ];
            $obj->save();

            UserDao::activation($uid);
        }
        $code = 1;
        $msg = '操作成功';
        exit(json_encode(['code' => $code, 'msg' => $msg, 'time' => $time]));
    }
}